package com.scy.service;

import cn.hutool.core.util.IdUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author：sichenyong
 * @Email: sichenyongwork@163.com
 * @Package：com.scy.service
 * @Project：Redis7NewDataStructure
 * @Date：2024/4/29 15:03
 * @description：
 */
@Service
@Slf4j
public class InventoryService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${server.port}")
    String port;

    public String sale() {
        String retMsg;
        String key = "scyRedisLock";
        String uuidValue = IdUtil.simpleUUID() + ":" + Thread.currentThread().getId();

        while (!stringRedisTemplate.opsForValue().setIfAbsent(key, uuidValue)) {
            try {
                TimeUnit.MICROSECONDS.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 拿到分布式锁
        try {
            //获取redis中的库存数据
            String inventory = stringRedisTemplate.opsForValue().get("inventory:001");

            int inventoryNumber = inventory == null ? 0 : Integer.parseInt(inventory);

            if (inventoryNumber > 0) {

                stringRedisTemplate.opsForValue().set("inventory:001",String.valueOf(-- inventoryNumber));
                retMsg = String.format("库存更新成功，当前库存：%s, 服务器端口：%s", inventoryNumber, port);
                log.info("库存更新成功，当前库存：{}, 服务器端口：{}", inventoryNumber, port);
            }
            else {
                retMsg = String.format("商品已经卖完了...... 服务器端口：%s",port);
                log.warn("商品已经卖完了...... 服务器端口：{}",port);
            }
        } finally {
            // TODO: 删除自己设置的锁
            stringRedisTemplate.delete(key);
        }


        return retMsg;
    }
}
